using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum BirdState
{
    Wariting,
    BeforeShoot,
    AfterShoot
}
public class Bird : MonoBehaviour
{
    public BirdState state = BirdState.BeforeShoot;

    private bool isMouseDown = false;
    public float maxDistance = 2.4f;

    public float flyspeed = 5;
    private Rigidbody2D rgd;
    void Start()
    {
        rgd = GetComponent<Rigidbody2D>();
       
    }

    // Update is called once per frame
    void Update()
    {
        switch (state)
        {
            case BirdState.Wariting:
                break;
            case BirdState.BeforeShoot:
                MoveControl();
                break;
            case BirdState.AfterShoot:
                break;
            default:
                break;
        }
        
    }
    private void OnMouseDown()
    {
        if(state == BirdState.BeforeShoot)
        {
            isMouseDown = true;
            Slingshot.instance.StartDraw(transform);
        }
    }
    private void OnMouseUp()
    {
        if(state == BirdState.BeforeShoot)
        {
            isMouseDown = false;
            Slingshot.instance.EndDraw();
            Fly();
        }
    }
    private void MoveControl()
    {
        if(isMouseDown)
        {
            transform.position = GetMousePosition();
        }
    }
    private Vector3 GetMousePosition()
    {
        Vector3 centerPositon = Slingshot.instance.getCenterPositon();
        Vector3 mp = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mp.z = 0;
        Vector3 mouseDir = mp - centerPositon;
        float distance = (mp - centerPositon).magnitude;
        if(distance > maxDistance)
        {
          mp = mouseDir.normalized * maxDistance + centerPositon;
        }
        return mp;
    }
    private void Fly()
    {
        rgd.bodyType = RigidbodyType2D.Dynamic;
        rgd.velocity = (Slingshot.instance.getCenterPositon() - transform.position).normalized * flyspeed;
        state = BirdState.AfterShoot;
    }
    public void GoStage(Vector3 position)
    {
        state = BirdState.BeforeShoot;
        transform.position = position;
    }
}
